//
//  HMPictureStatusView.swift
//  WeiBoXR
//
//  Created by acer on 16/9/25.
//  Copyright © 2016年 acer. All rights reserved.
//

import UIKit
import SDWebImage

private let collectionviewCellID = "collectionviewCellID"
let itemMargin: CGFloat = 5
let itemWidth = (ScreenWidth - 2 * HMHomeTVCellMargin - 2 * itemMargin) / 3

class HMPictureStatusView: UICollectionView {

    var picUrls: [HMStatusPictureInfo]? {
        didSet {
            
            messageLabel.text = "\(picUrls?.count ?? 0)"
            let size = calcSize(count: picUrls?.count ?? 0)
            self.snp_updateConstraints { (make) in
                make.size.equalTo(size)
            }
            reloadData()
        }
    }
    
    private lazy var messageLabel: UILabel = UILabel(textColor: UIColor.magenta, fontSize: 20)
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        layout.minimumLineSpacing = itemMargin
        layout.minimumInteritemSpacing = itemMargin

        super.init(frame: frame, collectionViewLayout: layout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        register(HMPictureViewCell.self, forCellWithReuseIdentifier: collectionviewCellID)
        dataSource = self
        backgroundColor = RandomColor()
        
        addSubview(messageLabel)
        
        messageLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self)
        }

    }
    
    private func calcSize(count: Int) -> CGSize {
        
        if count == 1 {
            let urlString = picUrls?.first?.thumbnail_pic!
            //  从缓存中去取图片
            let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: urlString)
            if image != nil {
                var size = image!.size
                if size.width < 80 {
                    let calwidth: CGFloat = 80
                    let height: CGFloat = size.height / size.width * calwidth
                    let calheight = height > 150 ? 150 : height
                    size.width = calwidth
                    size.height = calheight
                    size = CGSize(width: calwidth, height: calheight)
                }
//                size = CGSize(width: itemWidth, height: itemWidth)
                let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
                flowLayout.itemSize = size
                return size
            }
        }
        
        //  每项之间的间距
        let itemMargin: CGFloat = 5
        //  每项的宽度
        let itemWidth = (ScreenWidth - 2 * HMHomeTVCellMargin - 2 * itemMargin) / 3
        
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)

//        print(count)
        //  计算列数
        let cols = count > 3 ? 3 : count
        //  计算行数
        let rows = (count - 1) / 3 + 1
        //  计算当前配图宽度
        let currentWidth = itemWidth * CGFloat(cols) + CGFloat(cols - 1) * itemMargin
        //  计算当前配图的高度
        let currentHeight = itemWidth * CGFloat(rows) + CGFloat(rows - 1) * itemMargin
        
        return CGSize(width: currentWidth, height: currentHeight)

    }

}


extension HMPictureStatusView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionviewCellID, for: indexPath) as! HMPictureViewCell
//        cell.backgroundColor = RandomColor()
        cell.pictureModel = picUrls![indexPath.item]
        return cell
    }
}


class HMPictureViewCell: UICollectionViewCell {
    
    var pictureModel : HMStatusPictureInfo? {
        didSet {
            if let urlString = pictureModel?.thumbnail_pic {
                pictureImageV.sd_setImage(with: URL(string: urlString), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                //  判断后缀是否是.gif
                if urlString.hasSuffix(".gif") {
                    gifImageView.isHidden = false
                } else {
                    gifImageView.isHidden = true
                }

            }
        }
    }
    private lazy var pictureImageV = { () -> UIImageView in
        let view = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        return view
    }()
    //  gif图片
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(pictureImageV)
        contentView.addSubview(gifImageView)

        pictureImageV.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsets.zero)
        }
        gifImageView.snp_makeConstraints { (make) in
            make.bottom.equalTo(pictureImageV)
            make.trailing.equalTo(pictureImageV)
        }

    }
}
